package com.ruyuan.commodity.elasticsearch;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * es rest client 配置类
 */
@Configuration
public class EsRestClientConfig {

    /**
     * es集群ip地址
     */
    @Value("${es.cluster.ips}")
    private String[] esClusterIpAddressArray;

    @Autowired
    private Environment environment;

    /**
     * @return 返回es rest client客户端
     */
    @Bean
    public RestHighLevelClient highLevelClient() {
        System.out.println(environment);
        HttpHost[] httpHostArray = new HttpHost[esClusterIpAddressArray.length];
        for (int i = 0; i < esClusterIpAddressArray.length; i++) {
            String ip = esClusterIpAddressArray[i].split(":")[0];
            int port = Integer.parseInt(esClusterIpAddressArray[i].split(":")[1]);
            httpHostArray[i] = new HttpHost(ip, port);
        }

        RestClientBuilder restClientBuilder = RestClient.builder(httpHostArray);
        return new RestHighLevelClient(restClientBuilder);
    }



}